package com.myKng.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.AppendObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;

@Service
public class OssService {
    
    // OSS客户端配置参数
    private String endpoint = "your-oss-endpoint";
    private String accessKeyId = "your-access-key-id";
    private String accessKeySecret = "your-access-key-secret";
    private String bucketName = "your-bucket-name";
    
    // 初始化OSS客户端
    private OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
    /**
     * 追加写入文件
     * @param objectName 文件路径
     * @param content 内容
     * @return 文件长度
     */
    public long appendToFile(String objectName, String content) {
        try {
            // 获取当前文件长度
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            long position = ossObject.getObjectMetadata().getContentLength();
            
            // 创建追加请求
            AppendObjectRequest appendObjectRequest = new AppendObjectRequest(
                bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
            appendObjectRequest.setPosition(position);
            
            // 执行追加操作
            return ossClient.appendObject(appendObjectRequest).getNextPosition();
            
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
    
    /**
     * 覆盖写入文件
     * @param objectName 文件路径
     * @param content 内容
     * @return 是否成功
     */
    public boolean overwriteFile(String objectName, String content) {
        try {
            // 创建覆盖请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
            
            // 执行覆盖操作
            ossClient.putObject(putObjectRequest);
            return true;
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    // 关闭OSS客户端
    public void shutdown() {
        ossClient.shutdown();
    }
}